package com.atguigu.gmall.common.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gsy
 * @date 2021年09月13日18:09
 * Description
 */
@Configuration
public class DeadLetterConfig {
    public static final String exchange_dead = "exchange.dead";
    public static final String routing_dead_1 = "routing.dead.1";
    public static final String routing_dead_2 = "routing.dead.2";
    public static final String queue_dead_1 = "queue.dead.1";
    public static final String queue_dead_2 = "queue.dead.2";

    //交换机与死信交换机 合并
    @Bean
    public Exchange exchange(){
        return ExchangeBuilder.directExchange(exchange_dead).build();
    }

    //死信队列
    @Bean
    public Queue deadLetterQueue(){

        Map<String, Object> arguments =new HashMap<>();
        //设置队列延迟时间 ttl 毫秒
        arguments.put("x-message-ttl",10000);
        //配置死信交换机
        arguments.put("x-dead-letter-exchange",exchange_dead);
        //配置死信路由key
        arguments.put("x-dead-letter-routing-key",routing_dead_2);
        return QueueBuilder.durable(queue_dead_1).withArguments(arguments).build();
    }

    //普通队列
    @Bean
    public Queue queue(){
        return QueueBuilder.durable(queue_dead_2).build();
    }
    //绑定死信队列到交换机
    @Bean
    public Binding bindingDeadLetterQueueToexchange(@Qualifier("deadLetterQueue") Queue queue,
                                                    @Qualifier("exchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(routing_dead_1).noargs();
    }
    //绑定普通队列到死信交换机
    @Bean
    public Binding bindingQueueToDeadLetterExchange(@Qualifier("queue") Queue queue,
                                                    @Qualifier("exchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(routing_dead_2).noargs();
    }
}
